(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('hy5b/t/frontend')) :
  typeof define === 'function' && define.amd ? define(['frontend', 'css!./add-reduce.css'], factory) :
  global.addReduce = factory(t);
}(this, function (t) { 'use strict';

  var addReduce = function(options) {
    function setValue(val) {
      if (typeof options.set === 'function') {
        options.set(val)
      }
    }

    var elem = document.createElement('span')
    elem.className = 'hy5b-add_reduce'

    if (options.key) {
      var keyElem = document.createElement('span')
      keyElem.className = 'mr10'
      keyElem.innerHTML = options.key + ':'
      elem.appendChild(keyElem)
    }

    var val = options.val || 0;
    var delta = options.delta || 1
    
    var originValue = val

    var originValueElem = document.createElement('span')
    originValueElem.innerHTML = originValue
    originValueElem.className = 'ml10 text-show active'

    var valueElem = document.createElement('span')
    valueElem.className = 'ml10 text-show'

    originValueElem.addEventListener('click', function() {
      setValue(originValue);
      t.removeClass(valueElem, 'active');
      t.addClass(originValueElem, 'active');
    })

    valueElem.addEventListener('click', function() {
      setValue(val);
      t.removeClass(originValueElem, 'active');
      t.addClass(valueElem, 'active');
    })
    
    var btns = ['reduce', 'add', 'recovery']
    var btnElem;

    for (var i = 0; i < btns.length; i++) {
      btnElem = document.createElement('button')
      btnElem.className = 'btn btn-default'
      var btn = btns[i]
      btnElem.innerHTML = btn;
      btnElem.setAttribute('data-btn', btn)

      btnElem.addEventListener('click', function(e) {
        var btn = e.target.getAttribute('data-btn')

        switch (btn) {
          case 'add':
            val += delta;
            break;
          case 'reduce':
            val -= delta;
            break;
          case 'recovery':
            val = originValue;
            break;
        }

        setValue(val)

        t.removeClass(originValueElem, 'active')
        t.addClass(valueElem, 'active')
      
        valueElem.innerHTML = val
      })

      elem.appendChild(btnElem)
    }

    elem.appendChild(originValueElem)
    elem.appendChild(valueElem)
    
    var inputElem = document.createElement('input')
    inputElem.className = 'ml10'
    elem.appendChild(inputElem)
    
    inputElem.onkeyup = function(event) {
      if (event.keyCode == 13) {
        val = inputElem.value;
        try { val = parseFloat(val) } catch(e) {}
        setValue(val)

        t.removeClass(originValueElem, 'active')
        t.addClass(valueElem, 'active')
      
        valueElem.innerHTML = val
      }
    }
    
    return elem;
  }

  return addReduce

}))
